package com.japp.sys.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.japp.base.BaseService;
import com.japp.sys.bean.RoleBean;
import com.japp.sys.mapper.RoleMapper;
import com.japp.tools.common.JappLog;
import com.japp.tools.page.Page;

/**
 * 
 * @author Jion
 *角色管理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService implements BaseService {
	@Autowired
	private RoleMapper roleMapper;
	
	
	/**
	 * 分页查询
	 * @param page
	 * @param obj
	 * @return
	 */
	public Page<RoleBean> getPage(Page<RoleBean> page,RoleBean obj){
		return roleMapper.getPage(page, obj);
	}
	
	/**
	 * 查询所有角色
	 * @return
	 */
	public List<RoleBean> queryRoleAll() {
		return roleMapper.queryRoleAll();
	}
	/**
	 * 查询角色（ID）
	 * @return
	 */
	public RoleBean findRoleById(int id) {
		return roleMapper.findRoleById(id);
	}
	/**
	 * 更新角色
	 * @return
	 */
	public int updateRole(RoleBean role) {
		int rel = 0;
		try {
			rel = roleMapper.deleteRoleInfoById(role.getR_id());
			if(rel>0){
				JappLog.log.info("角色权限删除成功!");
			}
			rel = roleMapper.insertRoleInfo(role.getR_id(), role.getR_key().split(","));
			if(rel>0){
				JappLog.log.info("角色权限更新成功!");
			}
				rel = roleMapper.updateRole(role);
		} catch (Exception e) {
			if(e.getCause().getMessage().indexOf("违反唯一约束")!=-1){
				rel = 999;
				return rel;
			}
			e.printStackTrace();
			rel = 0;
		}
		
		return rel;
	}
	/**
	 * 添加角色
	 * @return
	 */
	public int insertRole(RoleBean role) {
		int id=0,rel=0;
		try {
			try {
				id = roleMapper.insertRole(role);
			} catch (Exception e) {
				if(e.getCause().getMessage().indexOf("违反唯一约束")!=-1){
					rel = 999;
					return rel;
				}
				rel = 0;
			}
			id = role.getR_id();
			if(id==0){
				JappLog.log.info("新增失败!");
				return 0;
			}
			//删除权限表
			rel = roleMapper.deleteRoleInfoById(id);
			if(rel>0){
				JappLog.log.info("角色权限删除成功!");
			}
			rel = roleMapper.insertRoleInfo(id, role.getR_key().split(","));
			if(rel>0){
				JappLog.log.info("角色权限更新成功!");
			}
		} catch (Exception e) {
			JappLog.log.error("",e);
			throw new RuntimeException("事物回滚");
		}
		return rel;
	}
	/**
	 * 删除角色
	 * @return
	 */
	public int deleteRoleById(String[] keys) {
		int rel = 0;
		if(keys!=null&&keys.length>0){
			rel = roleMapper.deleteRoleById(keys);
		}
		return rel;
	}
}
